package com.mazaiting.auth.security.core.userdetails.base;

import com.mazaiting.common.core.domain.result.ResultCode;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 用户详情服务基类
 *
 * @author mazaiting
 * @create_time 2022/9/26 21:43
 */
public abstract class BaseUserDetailsService implements UserDetailsService {

    /**
     * 校验用户详情信息
     * 如果存在异常则抛出运行时异常
     *
     * @param userDetails 用户详情信息
     */
    protected void checkUserDetails(UserDetails userDetails) {
        if (!userDetails.isEnabled()) {
            throw new DisabledException(ResultCode.USER_ACCOUNT_DISABLE.getMessage());
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException(ResultCode.USER_ACCOUNT_LOCKED.getMessage());
        } else if (!userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException(ResultCode.USER_ACCOUNT_EXPIRED.getMessage());
        } else if (!userDetails.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(ResultCode.USER_CREDENTIALS_EXPIRED.getMessage());
        }
    }

}
